import React,{
  useState,useRef,useEffect
} from 'react';
import './subFormDrag.less';

import {
  Input,Select,DatePicker,Popconfirm,
  Modal
} from 'antd';

import {
	DeleteOutlined,
	CopyOutlined,EditOutlined
} from '@ant-design/icons';

import {uuid} from '@/utils/utils';
import EditItemForm from './EditItemForm';

const {RangePicker}= DatePicker;

type PropsType = {
  onChange:Function;
  listData:any[]
}
function SubFormDrag(props:PropsType) {
  
  const [subFormItemIndex,setSubFormItemIndex] = useState<number>(-1);
  const subsRef = useRef<any>([]);
  const [subStartIndex,setSubStartIndex] = useState(-1);
  const [showEditDialog,setShowEditDialog] = useState(false);
  const [curItemConfig,setCurItemConfig] = useState<any>(null);
  const [editIndex,setEditIndex] = useState<any>([]);
  
  useEffect(() => {
    // console.log('subFormDrag render',subsRef)
    subsRef.current.forEach((sub:any) =>{
      sub && setRefStyle(sub);
    })
  })

  function  setRefStyle(sub:any) {
    sub.style.border = '0px';
    sub.style.borderRight = '1px solid #e3e3e3' ;
  }


  function onListClick(e:any,item:any,index:number){
    e.preventDefault()
    setSubFormItemIndex(index);
  }
  function removeSubFormItem(e:any,id:string,index:number) {
		e.preventDefault();
    const data:any = [...props.listData];
    data[index] = data[index].filter((v:any)=>v.id !== id);
    // console.log(data)
    props.onChange(data);

	}
	function copySubFormItem(e:any,item:any,index:number,index2:number) {
		e.preventDefault()
    const data:any = [...props.listData];
    const inx = index2 + 1;
    data[index].splice(inx,0,{...item,id:uuid()})
    // console.log(data)
    props.onChange(data);
	}
	function editSubFormItem(e:any,item:any,index:number,index2:number) {
		e.preventDefault();
    // console.log(item);
    setShowEditDialog(true);
    setCurItemConfig(item);
    setEditIndex([index,index2]);
    // const data:any = [...props.listData];
    // const inx = index2 + 1;
    // data[index].splice(inx,0,{...item,id:uuid()})
    // // console.log(data)
    // props.onChange(data);
	}

  function onItemEditData(itemConfig:any){
    const [index,index2] = editIndex;
    const data:any = [...props.listData];
    // data[index][index2]
    // console.log(data);
    // console.log(data[index][index2]);
    data[index][index2] = itemConfig;
    props.onChange(data);
  }

  function onSubDragStart(e:any,index2:number){
    // console.log('onSubDragStart',e,index2)
    setSubStartIndex(index2);
  }
  function onSubDragOver(e:any,item:any,index2:number){
    e.preventDefault();
    let tag = e.target.parentNode;
    // console.log('onSubDragOver',e,item,index2)
    // return console.log(target.parentNode.id)
    
    if(tag.id === 'subItem') {
     tag.style.border = '1px dashed #009da9' 
    //  console.log(subsRef.current);
     subsRef.current.forEach((item2:any,inx:number)=>{
        if(inx !== index2){
          item2 && setRefStyle(item2);
        }
      })
    }

  }


  function onSubDrop(e:any,item:any,index2:number){
    // console.log('onSubDrop',e,item,index2)
    if(subStartIndex < 0) return;

    let data:any = [...props.listData];
    const startData = {...data[0][subStartIndex]};
    data[0] = data[0].filter((v:any)=>v.id !== startData.id)
    startData.id = uuid();
    data[0].splice(index2,0,startData);
    props.onChange(data);

    setSubStartIndex(-1);
  }

  function setItemWidth(item:any){
    const w = 160;
    switch(item.subFormCompSpan){
      case '1/2': return w / 2 ;
      case '1/1': return w ;
      case '2': return w * 2 ;
    }
    return item.subFormCompWidth;
  }

  const renderArr = [props.listData[0]];
  return (
    <div className="subFormDrag"  >
      <div className="sub-form-box">

        {renderArr.map((list:any,index:number) =>(
          <div className="item-col" key={index} style={{width:(list.length + 1) * 160 - 68 + 'px'}}>
            <div className="seq">
              <span className="item-label"></span>
              <span className="item-field">1</span>
            </div>
            {
              list.map((item:any,index2:number)=>(
                <div 
                  className={"item" + (subFormItemIndex === index2 ? ' sub-act' : '') } 
                  style={{width:setItemWidth(item) + 'px'}}
                  id="subItem"
                  ref={f=>{subsRef.current[index2]=f}}
                  key={item.id} 
                  onClick={(e)=>onListClick(e,item,index2)}
                  draggable={true}
                  onDragStart={(e)=>onSubDragStart(e,index2)}
                  onDragOver={(e)=>onSubDragOver(e,item,index2)} 
                  onDrop={(e)=>onSubDrop(e,item,index2)}
                >
                  <span className="item-label">{item.showTitle && item.title}</span>
                  <span className="item-field">
                    {
                      item.name === 'input' ? (
                        item.props.textarea ? <Input.TextArea size="small" style={{resize:'none'}} disabled placeholder={item.props.tip} /> : <Input placeholder={item.props.tip} size="small" disabled />
                      )
                      : item.name === 'select' ? <Select size="small" style={{width:'100%'}} disabled />
                      : item.name === 'datePicker' ? <DatePicker size="small"  disabled />
                      : item.name === 'dateRange' ? <RangePicker size="small" disabled />
                      : null
                    }
                  </span>
                  {
                    subFormItemIndex === index2 ? (
                      <div className="editbar">
                        <EditOutlined className="edit" onClick={(e)=>{editSubFormItem(e,item,index,index2)}} />
                        <Popconfirm
                          title="确认删除该组件吗？"
                          onConfirm={(e)=>removeSubFormItem(e,item.id,index)}
                          okText="确认"
                          cancelText="取消"
                        >
                          <DeleteOutlined className="del" />
                        </Popconfirm>
                        <CopyOutlined className="copy" onClick={(e)=>{copySubFormItem(e,item,index,index2)}} />
                      </div>
                    ): null
                  }
                </div>
              ))
            }
          </div>
        ))}
        
      </div>

      <Modal
          title="子组件编辑"
          visible={showEditDialog}
          footer={null}
          mask={false}
          onCancel={()=>{setShowEditDialog(false)}}
          width={600} 
          style={{height:'500px',right:'10px'}}
          className="subFormEditDialog"
        >
          
          <EditItemForm 
            itemConfig={curItemConfig} 
            onItemEditData={onItemEditData}
          />
        
      </Modal>
    </div>
  )
}
export default SubFormDrag;